import React from 'react'
import { ArrowUpOutlined } from '@ant-design/icons'
import './index.css'

class ReturnTop extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            returnTopDisplay: false
        }
    }

    handleScroll = () => {
        if (document.body.scrollTop > 120 || document.documentElement.scrollTop > 120) {
            if (this.state.returnTopDisplay === false) this.setState({ returnTopDisplay: true })
            else return
        } else {
            if (this.state.returnTopDisplay === true) this.setState({ returnTopDisplay: false })
            else return
        }
    }

    scrollToTop = () => {
        const c = Math.max(
            document.documentElement.scrollTop,
            document.body.scrollTop,
            0 // 防止负值
        );

        // 终止条件：当滚动距离小于等于1像素时停止
        if (c <= 5) {
            this._scrollId && window.cancelAnimationFrame(this._scrollId);
            this._scrollId = null;
            return window.scrollTo(0, 0);
        }

        const target = c - (c / 8);

        // 执行滚动
        window.scrollTo(0, target);

        // 存储动画帧ID用于后续取消
        this._scrollId = requestAnimationFrame(this.scrollToTop);
    }

    async componentDidMount() {
        window.addEventListener('scroll', this.handleScroll) //滚动条监视
    }

    async componentWillUnmount() {
        window.removeEventListener('scroll', this.handleScroll)
    }

    render() {
        if (this.state.returnTopDisplay === true) {
            return (
                <div className='ReturnTop-main'
                    onClick={this.scrollToTop}
                >
                    <ArrowUpOutlined />
                </div>
            )
        } else return ''
    }
}

export default ReturnTop
